'use strict';

const RouterService = require('./base');

class ProductService extends RouterService {
  constructor(ctx) {
    super(ctx, 'Product');
  }

  pageOrder() {
    return [['sort', 'ASC'], ['id', 'DESC']];
  }

  listOrder() {
    return [['sort', 'ASC'], ['id', 'DESC']];
  }

  // 重写getPage方法，增加分类信息
  async getPage(where, page, pageSize) {
    const { app } = this.ctx;
    const include = [{
      model: app.model.Category,
      as: 'category',
      attributes: ['id', 'name'],
    }];
    return super.getPage(where, page, pageSize, include);
  }

  // 检查商品在指定日期的库存是否充足
  async checkStock(productId, date, count) {
    const { app } = this.ctx;
    
    // 获取商品信息
    const product = await app.model.Product.findByPk(productId);
    if (!product || product.status !== 1) {
      return false;
    }

    // 获取指定日期的预定总人数
    const reservedCount = await app.model.Reservation.sum('personCount', {
      where: {
        productId,
        reserveDate: date,
        status: {
          $in: [1, 2] // 待确认和已确认的预定
        }
      }
    }) || 0;

    // 检查是否超出每日库存
    return (reservedCount + count) <= product.stock;
  }

  // 获取可预定时间段
  getAvailableTimeSlots() {
    return [
      '11:30-12:30',
      '12:30-13:30',
      '17:30-18:30',
      '18:30-19:30',
      '19:30-20:30'
    ];
  }
}

module.exports = ProductService;
